package tech.aichan.AiQA.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import tech.aichan.AiQA.common.ErrorCode;
import tech.aichan.AiQA.esrepo.ItemESRepo;
import tech.aichan.AiQA.exception.ThrowUtils;
import tech.aichan.AiQA.mapper.ItemMapper;
import tech.aichan.AiQA.model.dto.item.ItemUpdateRequest;
import tech.aichan.AiQA.model.entity.Item;
import tech.aichan.AiQA.model.entity.es.ItemES;
import tech.aichan.AiQA.model.vo.ItemVO;
import tech.aichan.AiQA.service.ItemService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mengyu
 * @date 2024/03/03 9:26
 */
@Service
@Slf4j
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {
//    @Resource TODO
    private ItemESRepo itemESRepo;

    @Override
    public void addItem(String itemName, List<String> tags, Double price) {
        Item item = new Item();
        item.setItemName(itemName);
        item.setTags(String.join(",", tags));
        item.setPrice(price);
        int insert = this.getBaseMapper().insert(item);
        ThrowUtils.throwIf(insert == 0, ErrorCode.SYSTEM_ERROR, "数据库异常");
        // 插入到ES中
        ItemES itemES = new ItemES();
        BeanUtil.copyProperties(item, itemES);
        itemESRepo.save(itemES);
    }

    @Override
    public void updateItem(ItemUpdateRequest itemUpdateRequest) {
        Long id = itemUpdateRequest.getId();
        Item item = this.getBaseMapper().selectById(id);
        BeanUtil.copyProperties(itemUpdateRequest, item);
        int i = this.getBaseMapper().updateById(item);
        ThrowUtils.throwIf(i == 0, ErrorCode.SYSTEM_ERROR, "数据库异常");
        // 更新es
        ItemES itemES = new ItemES();
        BeanUtil.copyProperties(itemUpdateRequest, itemES);
        itemESRepo.save(itemES);
    }

    @Override
    public void deleteItem(Long id) {
        int i = this.getBaseMapper().deleteById(id);
        ThrowUtils.throwIf(i == 0, ErrorCode.SYSTEM_ERROR, "数据库异常");
        // 删除es
        itemESRepo.deleteById(id);
    }

    @Override
    public Page<ItemVO> getItem(String all, Integer page, Integer size, Boolean priceAsc, Boolean dateAsc) {
        ThrowUtils.throwIf(priceAsc != null && dateAsc != null,ErrorCode.OPERATION_ERROR,"不允许同时排序price和createTime");
        // field
        String sortBy = (priceAsc != null) ? "price" : "createTime";
        boolean isAscending = (priceAsc != null) ? priceAsc : Boolean.TRUE.equals(dateAsc);
        Sort sort = isAscending ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending();
        Pageable pageable = PageRequest.of(page, size, sort);
        // all
        Page<ItemES> esResult = StrUtil.isBlankIfStr(all) ? itemESRepo.findAll(pageable) : itemESRepo.findByAll(all, pageable);
        // result
        if (esResult.getTotalElements() == 0) {
            return new PageImpl<>(Collections.emptyList(), esResult.getPageable(), 0);
        }
        List<ItemVO> itemVOS = esResult.getContent().stream()
                .map(i -> {
                    ItemVO itemVO = new ItemVO();
                    BeanUtil.copyProperties(i, itemVO);
                    return itemVO;
                })
                .collect(Collectors.toList());
        return new PageImpl<>(itemVOS, esResult.getPageable(), esResult.getTotalElements());
    }

}
